<template>
  <div class="signalr-test">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>SignalR连接测试</span>
        </div>
      </template>
      
      <div class="test-content">
        <div class="status-section">
          <h3>连接状态</h3>
          <el-tag :type="connectionStatus ? 'success' : 'danger'" size="large">
            {{ connectionStatus ? '已连接' : '未连接' }}
          </el-tag>
          <p>连接ID: {{ connectionId || '未连接' }}</p>
        </div>
        
        <div class="actions-section">
          <h3>操作</h3>
          <el-button @click="connect" type="primary" :loading="connecting">
            连接SignalR
          </el-button>
          <el-button @click="disconnect" type="danger" :disabled="!connectionStatus">
            断开连接
          </el-button>
          <el-button @click="testReceive" type="warning" :disabled="!connectionStatus">
            测试接收数据
          </el-button>
        </div>
        
        <div class="logs-section">
          <h3>连接日志</h3>
          <div class="log-container">
            <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
          <el-button @click="clearLogs" size="small">清空日志</el-button>
        </div>
        
        <div class="data-section">
          <h3>接收到的数据</h3>
          <div class="data-container">
            <pre>{{ JSON.stringify(receivedData, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { signalRService } from './eo'
import http from '@/http/axiosHelper'
const connectionStatus = ref(false)
const connectionId = ref('')
const connecting = ref(false)
const logs = ref<Array<{time: string, message: string, type: string}>>([])
const receivedData = ref<any>(null)

// 添加日志
const addLog = (message: string, type: 'info' | 'error' | 'success' = 'info') => {
  const time = new Date().toLocaleTimeString()
  logs.value.push({ time, message, type })
  console.log(`[${time}] ${message}`)
}

// 连接SignalR
const connect = async () => {
  try {
    connecting.value = true
    addLog('开始连接SignalR...', 'info')
    
    await signalRService.createConnection()
    connectionStatus.value = signalRService.getConnectionStatus()
    const connection = signalRService.getConnection()
    
    if (connection) {
      connectionId.value = connection.connectionId || '未知'
      addLog(`连接成功，连接ID: ${connectionId.value}`, 'success')
      
      // 设置数据接收监听器
      signalRService.onReceiveEnterOutData((data: any) => {
        addLog(`收到数据: ${JSON.stringify(data)}`, 'success')
        receivedData.value = data
      })
      
      ElMessage.success('SignalR连接成功')
    } else {
      addLog('连接失败：无法获取连接实例', 'error')
      ElMessage.error('SignalR连接失败')
    }
  } catch (error) {
    addLog(`连接失败: ${error}`, 'error')
    ElMessage.error('SignalR连接失败')
  } finally {
    connecting.value = false
  }
}

// 断开连接
const disconnect = async () => {
  try {
    await signalRService.stopConnection()
    connectionStatus.value = false
    connectionId.value = ''
    addLog('连接已断开', 'info')
    ElMessage.success('连接已断开')
  } catch (error) {
    addLog(`断开连接失败: ${error}`, 'error')
    ElMessage.error('断开连接失败')
  }
}

// 测试接收数据
const testReceive = () => {
  addLog('测试数据接收功能...', 'info')
  // 这里可以模拟一些测试数据
  const testData = {
    id: 1,
    code: "TEST001",
    dateTime: new Date().toISOString(),
    state: 2,
    depotName: "测试仓库",
    incomingQuantity: 100
  }
  receivedData.value = testData
  addLog(`测试数据: ${JSON.stringify(testData)}`, 'success')
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 监听连接状态变化
const checkConnectionStatus = () => {
  const currentStatus = signalRService.getConnectionStatus()
  if (currentStatus !== connectionStatus.value) {
    connectionStatus.value = currentStatus
    addLog(`连接状态变化: ${currentStatus ? '已连接' : '未连接'}`, 'info')
  }
}

// 定期检查连接状态
let statusCheckInterval: number

onMounted(() => {
  addLog('SignalR测试页面已加载', 'info')
  statusCheckInterval = setInterval(checkConnectionStatus, 2000)
})

onUnmounted(() => {
  if (statusCheckInterval) {
    clearInterval(statusCheckInterval)
  }
})
</script>

<style scoped>
.signalr-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-section, .actions-section, .logs-section, .data-section {
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 15px;
}

.status-section h3, .actions-section h3, .logs-section h3, .data-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.actions-section {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 10px;
  background-color: #FAFAFA;
  margin-bottom: 10px;
}

.log-item {
  display: flex;
  gap: 10px;
  margin-bottom: 5px;
  font-family: monospace;
  font-size: 12px;
}

.log-time {
  color: #909399;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-item.info .log-message {
  color: #409EFF;
}

.log-item.error .log-message {
  color: #F56C6C;
}

.log-item.success .log-message {
  color: #67C23A;
}

.data-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 10px;
  background-color: #FAFAFA;
}

.data-container pre {
  margin: 0;
  font-family: monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style> 